package cn.yunhe.servlet;

import cn.yunhe.beans.User;
import cn.yunhe.service.IUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author Juni
 * @date 2021/1/21
 * Servlet相当于控制层
 *  接收前台发送的请求，根据请求调用业务层相关的功能，将执行的结果返回给前台
 */
@WebServlet("/webServlet")
public class WebServletTest extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        PrintWriter out = resp.getWriter();
        //读取spring的配置文件
        WebApplicationContext wac =
                (WebApplicationContext) request.getServletContext().
                        getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        //Spring和Servlet都是容器，他们之间存在加载顺序的问题
        IUserService userService = wac.getBean(IUserService.class);
        List<User> userList = userService.querUsers();
        //将java实体类对象转换json字符串
        String data = JSON.toJSONString(userList);
        out.write(data);
        out.close();
    }
}
